#ifndef __M_UTIL_H__
#define __M_UTIL_H__
/* util 
 * 1. get now time 
 * 2. check file exist
 * 3. get path of file name 
 * 4. create directory
 *
 * */
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>


/*防止与标准库冲突*/
namespace log {
    namespace util {
        class Date {
        public:
            static size_t get_time() {
                return (size_t)time(nullptr);
            }
        };
        class File {
        public:
            static bool is_exist(const std::string &path_name) {
                /*access, 只在Linux下有效*/
                //return access(path_name.c_str(), F_OK) == 0;
                
                // stat, 遵循Posix, both Linux and window support 
                struct stat st;
                if (stat(path_name.c_str(), &st) < 0) {
                    return false;
                }
                return true;
            }
            static std::string get_path(const std::string &path_name) {
                /* ./abc/def/test.c  */
                // '/'是Linux下目录分隔符，'\\'是Windows下目录分隔符
                size_t pos = path_name.find_last_of("/\\");
                if (pos == std::string::npos) return ".";
                std::string path = path_name.substr(0, pos);
                return path;
            }
            static bool create_directory(const std::string &path_name) {
                /* ./abc/def/test.c  */
                size_t pos = 0, idx = 0;
                size_t len = path_name.size();
                while (idx < len) {
                    // 找到当前目录
                    pos = path_name.find_first_of("/\\", idx);
                    if (pos == std::string::npos) {
                        
                        int n = mkdir(path_name.c_str(), 0777);
                        return n == 0;
                    }
                    // 取子串
                    std::string parent_dir = path_name.substr(0, pos + 1);
                    // 创建目录
                    //if (parent_dir == "." || parent_dir == "..") { idx = pos + 1; continue; }
                    if (is_exist(parent_dir)) { idx = pos + 1; continue; }
                    int n = mkdir(parent_dir.c_str(), 0777);
                    if (n == -1) return false;

                    idx = pos + 1;
                }
                return true;
            }
        };
    }
}
#endif
